/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejemplo;

import control.ConexionDB;
import java.awt.event.KeyEvent;
import java.sql.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author alexis
 */
public class EjemploJList extends javax.swing.JFrame {

    //crea un objeto ConexionDB y Connection para conectarse a la base de datos
    ConexionDB conexionBaseDeDatos;
    Connection conexion;
    
    DefaultTableModel modelo;
    boolean cambios = false;
    int filaEditada;
    int columnaEditada;

    public EjemploJList() {
       
        initComponents();
   
       //establece la conexion
       conexionBaseDeDatos = new ConexionDB();
       conexion = conexionBaseDeDatos.establecerConexion();
    
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        consultarB = new javax.swing.JButton();
        editarB = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                jTable1ComponentAdded(evt);
            }
        });
        jTable1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTable1FocusLost(evt);
            }
        });
        jTable1.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                jTable1InputMethodTextChanged(evt);
            }
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
                jTable1CaretPositionChanged(evt);
            }
        });
        jTable1.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                jTable1AncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTable1KeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        consultarB.setText("consultar");
        consultarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultarBActionPerformed(evt);
            }
        });

        editarB.setText("editar");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(152, 152, 152)
                        .addComponent(consultarB)
                        .addGap(92, 92, 92)
                        .addComponent(editarB, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(consultarB)
                    .addComponent(editarB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(16, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void consultarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultarBActionPerformed
                
        //Creamos un string que contiene la sentencia SQL que vamos a ejecutar
        String sentenciaSQL = "SELECT idCalle, nombre FROM callespoblaciones LIMIT 20;";
        
        //creamos un resultset para guardar los resultados de la consulta
        ResultSet resultados = null;
        
        try {
            
            //creamos un objeto statement, ejecutamos la sentencia que teniamos en el string, guardamos en la variable resultados
            Statement sentencia = conexion.createStatement();
            resultados = sentencia.executeQuery(sentenciaSQL);
            
            //poner los resultados en el JTable
            modelo = new DefaultTableModel();
            jTable1.setModel(modelo);

            modelo.addColumn("id");
            modelo.addColumn("nombre");
           
            //mientras hayan resultados los guardamos en la tabla
            while(resultados.next()) {
                    // Se crea un array que será una de las filas de la tabla.
                    Object [] fila = new Object[3];
                    // Se rellena cada posición del array con una de las columnas de la tabla en base de datos.
                    for (int i=0;i<2;i++)
                         fila[i] = resultados.getObject(i+1);
                    // Se añade al modelo la fila completa.
                    modelo.addRow(fila); 
            }
            sentencia.close();
            resultados.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }  
    }//GEN-LAST:event_consultarBActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            conexion.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        System.out.println("ConexionFinalizada");
    }//GEN-LAST:event_formWindowClosing

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
       String nuevoValor = modelo.getValueAt(filaEditada, columnaEditada).toString();
       String idFilaEditada = modelo.getValueAt(filaEditada, 0).toString();   
            if(cambios){
                    System.out.println("ha clickeado y hay cambios");
                try {
            
                      PreparedStatement sentencia = conexion.prepareStatement("UPDATE callespoblaciones SET nombre= ? Where idCalle =?");
           
                      sentencia.setString(1, nuevoValor);
                      sentencia.setString(2, idFilaEditada);
                      sentencia.executeUpdate();
            
                      sentencia.close();

                     } catch (Exception ex) {
                             ex.printStackTrace();
 
                     }  
                
                cambios = false;
            }
         
    }//GEN-LAST:event_jTable1MouseClicked

    private void jTable1InputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jTable1InputMethodTextChanged
       
    }//GEN-LAST:event_jTable1InputMethodTextChanged

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
     
    }//GEN-LAST:event_jTable1KeyPressed

    private void jTable1CaretPositionChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jTable1CaretPositionChanged
     
    }//GEN-LAST:event_jTable1CaretPositionChanged

    private void jTable1AncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_jTable1AncestorAdded
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1AncestorAdded

    private void jTable1ComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_jTable1ComponentAdded
     
        filaEditada = jTable1.getSelectedRow();
        columnaEditada = jTable1.getSelectedColumn();   
        cambios = true;
    }//GEN-LAST:event_jTable1ComponentAdded

    private void jTable1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTable1FocusLost

    }//GEN-LAST:event_jTable1FocusLost

    private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyReleased

        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            String nuevoValor = modelo.getValueAt(filaEditada, columnaEditada).toString();
            String idFilaEditada = modelo.getValueAt(filaEditada, 0).toString();   
            if(cambios){
                    System.out.println("ha presionado enter y hay cambios");
                try {
            
                      PreparedStatement sentencia = conexion.prepareStatement("UPDATE callespoblaciones SET nombre= ? Where idCalle =?");
           
                      sentencia.setString(1, nuevoValor);
                      sentencia.setString(2, idFilaEditada);
                      sentencia.executeUpdate();
                      sentencia.close();

                     } catch (Exception ex) {
                             ex.printStackTrace();
                        }  
                cambios = false;
            }
        }
       
    }//GEN-LAST:event_jTable1KeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new EjemploJList().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton consultarB;
    private javax.swing.JButton editarB;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
